<?php
include_once 'application/controllers/AbstractController.php';
require_once 'application/models/Menu.php';
require_once 'application/models/MenuPrincipal.php';
require_once 'application/models/SousMenu.php';
require_once 'application/models/Utilisateur.php';

class MenuPrincipalController extends AbstractController 
{
	private static $_VISIBILITY_PUBLIC_READ = 0;
	private static $_VISIBILITY_PUBLIC_WRITE = 1;
	private static $_VISIBILITY_PRIVATE = 2;
	
	function indexAction()
    {
		parent::indexAction();
    	HttpUtil::do405();
    }
    
    
    function getAction()
    {
		parent::getAction();
    	HttpUtil::do405();
    }
    
    function postAction()
    {
		parent::postAction();
		$name = $this->getRequest()->getParam('nom');
		
		$isValid = TypeChecker::validate(array(
			array('data' => $name, 'type' => TypeChecker::$_TEXT_TYPE, 'name' => 'nom')
		));
		if ($isValid !== true) {
			HttpUtil::do400('validation', $isValid);
		}
		
		$menuId = $this->user->private_menu_id;
		$table = new MenuPrincipal();
		
		// get sort_order
		$whereSortOrder = $table->getAdapter()->quoteInto('menu_id = ?', $menuId);
		$orderby = array('sort_order desc');
	    $menuRows = $table->fetchAll($whereSortOrder, $orderby, 1);
	    $sortOrder = 1;
	    if (isset($menuRows[0])) {
	    	$sortOrder = $menuRows[0]['sort_order'] + 1;
	    }
		    
		// insert data
		try {
			$data = array(
				'nom' => $name,
				'sort_order' => $sortOrder,
				'menu_id' => $menuId
			);
			 
			$lastInsertId = $table->insert($data);	    
		}catch(Exception $exception) {
			HttpUtil::do400('creation_failed');
		}
			
   		$this->view->data = json_encode(array(
   			'id' => $lastInsertId,
   			'sort_order' => $sortOrder,
   			'menu_id' => $menuId,
   			'nom' => $name
   		));
    }
    
    function putAction()
    {
		parent::putAction();
    	HttpUtil::do405();
	}
    
    
    
    function deleteAction()
    {
		parent::deleteAction();
		
		$id = $this->getRequest()->getParam('id');
		
		$table = new MenuPrincipal();
		if ($this->user->private_menu_id > 0) {
			try {
				$menuRows = $table->find($id);
				$currentMenu = $menuRows->current();
				$currentMenu->delete();
			}catch(Exception $exception) {
				//TODO: rollback !!!
				HttpUtil::do400('delete_failed');
			}
		}
    }
}
